package com.spring;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyApplicationContext {
   private Class configClass;
   //单例池
   private ConcurrentHashMap<String,Object> singletonObjects= new ConcurrentHashMap<>();
   //bean的定义
   private ConcurrentHashMap<String,BeanDefinition> beanDefinitionMap= new ConcurrentHashMap<>();

    public MyApplicationContext(Class configClass) {
        this.configClass = configClass;

        //解析配置类
        //ComponentScan解析-->扫描路径-->扫描-->BeanDefinition--->BeanDefinitionMap
        scan(configClass);

        for (Map.Entry<String,BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName=entry.getKey();
            BeanDefinition beanDefinition=entry.getValue();
            if(beanDefinition.getScope().equals("singleton")){
                Object bean = createBean(beanName,beanDefinition);//单例Bean
                singletonObjects.put(beanName,bean);
            }
        }

    }


    public Object createBean(String beanName,BeanDefinition beanDefinition){
        Class clazz=beanDefinition.getClazz();
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();
            //对属性进行赋值，依赖注入
            for (Field declaredField : clazz.getDeclaredFields()) {
                if ((declaredField.isAnnotationPresent(AutoWired.class))){
                    Object bean = getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance,bean);
                }
                }
            if(instance instanceof BeanNameAware){
                    ((BeanNameAware) instance).setBeanName(beanName);
            }

             return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void scan(Class configClass) {
        ComponentScan componentScan = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path=componentScan.value();//扫描路径
        path=path.replace(".","/");

        //扫描路径下所有类
        ClassLoader classLoader=MyApplicationContext.class.getClassLoader();    //app
        URL resource = classLoader.getResource(path);
        File file=new File(resource.getFile());
        if(file.isDirectory()){
            File[] files = file.listFiles();

            for (File f : files) {
                String fileName=f.getAbsolutePath();
                if(fileName.endsWith(".class")) {
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                   className= className.replace("\\", ".");

                    try {

                        Class<?> clazz = classLoader.loadClass(className);

                        if (clazz.isAnnotationPresent(Component.class)) {
                            //表示当前类是一个Bean
                            //判断当前bean时单例Bean还是原prototype的bean
                             //BeanDefinition
                            Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            //通过注解获取beanName
                            String beanName = componentAnnotation.value();

                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setClazz(clazz);
                            //再判断作用域,并将作用域值设入beanDefinition
                            if(clazz.isAnnotationPresent(Scope.class)) {
                                Scope scopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            }else {
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    public Object getBean(String beanName){
            if(beanDefinitionMap.containsKey(beanName)){
                BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
                if(beanDefinition.getScope().equals("singleton")){
                    Object o = singletonObjects.get(beanName);
                    return o;
                }else{
                    //创建Bean对象
                    Object bean = createBean(beanName,beanDefinition);
                    return bean;
                }

            }else{
                //不存在对应的Bean
                throw  new NullPointerException();
            }

    }
}
